﻿using Fleck;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebSocket.Core
{
    internal static class WebSocketDataManager
    {
        public static Dictionary<string, IWebSocketConnection> SocketUsers = new Dictionary<string, IWebSocketConnection>();

        public static IWebSocketConnection GetSocketSession(string token)
        {
            if (string.IsNullOrEmpty(token)) return null;
            if (SocketUsers.Keys.Contains(token))
                return SocketUsers[token];
            return null;
        }

        public static void AddUser(string token, IWebSocketConnection session)
        {
            if (string.IsNullOrEmpty(token)) return;
            if (!SocketUsers.Keys.Contains(token))
                SocketUsers.Add(token, session);
            else
                SocketUsers[token] = session;
        }

        public static void RemoveUserSession(string token)
        {
            if (string.IsNullOrEmpty(token)) return;
            if (SocketUsers.Keys.Contains(token))
                SocketUsers.Remove(token);
        }

        public static void RemoveUserSessionBySessionId(Guid sessionId)
        {
            var dic = SocketUsers.SingleOrDefault(a => a.Value.ConnectionInfo.Id == sessionId);
            if (!string.IsNullOrEmpty(dic.Key))
                SocketUsers.Remove(dic.Key);
        }
    }
}
